<?php

namespace app\api\model;

use think\Db;

class MallOrderFanli extends Common
{
    protected $connection = 'database';

    public static function Add($order_id = 0)
    {
        $order = Db::connect(getenv('APP_MALL_DATABASE'))->name('mall_order')->master()->find($order_id);
        $orderItems = Db::connect(getenv('APP_MALL_DATABASE'))->name('mall_order_item')->master()->where(['order_id'=>$order_id])->select();
        $good_ids = array_column($orderItems, 'goods_id');
        $goods = Db::connect(getenv('APP_MALL_DATABASE'))->name('mall_goods')->where(['id'=>['in', $good_ids], 'fanli'=>1, 'fanli_rate'=> ['between', [0, 100]], 'fanli_day'=> ['>', 0]])->column('fanli_rate,fanli_day', 'id');

        $fanli_inserts = [];
        $timenow = time();
        $apprate = getenv('APP_RATE');
        foreach ($orderItems as $key => $value) {
            if (!isset($goods[$value['goods_id']])) continue;
            $good = $goods[$value['goods_id']];

            $fanli_inserts[] = [
                'user_id'=>$order['uid'],
                'order_item_id'=>$value['id'],
                'order_id'=>$value['order_id'],
                'goods_id'=>$value['goods_id'],
                'fanli_rate'=>$good['fanli_rate'],
                'fanli_count'=>number_format($value['num'] * $value['price'] * $apprate * $good['fanli_rate'] / 100, 2, '.', ''),
                'fanli_day'=>$good['fanli_day'],
                'fanli_day_rate'=>1 / $good['fanli_day'] * 100,
                'create_time'=>$timenow,
            ];
        }

        IF (sizeof($fanli_inserts)) {
            Db::connect(getenv('APP_MALL_DATABASE'))->name('mall_order_fanli')->insertAll($fanli_inserts);
        }
    }

    public static function setStatus($oredr_id, $status = 1)
    {
        $update = ['state'=>$status];
        if ($status==1) {
            $update['start_time'] = time();
        }
        Db::connect(getenv('APP_MALL_DATABASE'))->name('mall_order_fanli')->where(['order_id'=>$oredr_id])->update($update);
    }
}
